﻿using MPSystem.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Windows;
using System.Windows.Input;
using Ay.MvcFramework;
using Ay.Framework.DataCreaters;
using Ay.Framework.WPF;
using Ay.Framework.WPF.Controls;
using MPSystem.Execl;
using System.Data;
using System.Threading;
using Base.BLL;
using System.Windows.Navigation;
using MPSystem.Views.YFQ;
using System.Windows.Forms;
using MPSystem.Util;

namespace MPSystem.Controllers
{

    public class DataQuery_ZCAnalysisController : Controller
    {
        public static DataQuery_ZCAnalysisController Me = null;
        Common common = new Common();
        public static int gzmbh = 0;
        List<Dictionary<string, string>> conditons = new List<Dictionary<string, string>>();
        private string bh = "", dtStart = "", dtEnd = "", _sfbj = "", _jq = "", zbhs = "", _byZBH = "true", DW = "MPa";

        public ObservableCollection<DataQuery_ZCAnalysisModel> AllDatas { get; set; } = new ObservableCollection<DataQuery_ZCAnalysisModel>();
        public DataQuery_ZCAnalysisModelSearchModel SearchModel { get; set; } = new DataQuery_ZCAnalysisModelSearchModel();

        private AyPagingDto<DataQuery_ZCAnalysisModel> _Result;

        /// <summary>
        /// 未填写
        /// </summary>
        public AyPagingDto<DataQuery_ZCAnalysisModel> Result
        {
            get { return _Result; }
            set { Set(ref _Result, value); }
        }


        private ObservableCollection<IAyCheckedItem> _QCCbo = new ObservableCollection<IAyCheckedItem>();

        public ObservableCollection<IAyCheckedItem> QCCbo
        {
            get { return _QCCbo; }
            set { Set(ref _QCCbo, value); }
        }
        private ObservableCollection<IAyCheckedItem> _GZMCbo = new ObservableCollection<IAyCheckedItem>();

        public ObservableCollection<IAyCheckedItem> GZMCbo
        {
            get { return _GZMCbo; }
            set { Set(ref _GZMCbo, value); }
        }

        private bool _IsBusy = false;
        public bool IsBusy
        {
            get { return _IsBusy; }
            set { Set(ref _IsBusy, value); }
        }
        /// <summary>
        /// 搜索
        /// </summary>
        public ActionResult Search { get; private set; }

        /// <summary>
        /// 搜索
        /// </summary>
        public ActionResult ExportExecl { get; private set; }

        public ActionResult CqChanged { get; private set; }

        public DataQuery_ZCAnalysisController() : base()
        {
            Me = this;
            Result = new AyPagingDto<DataQuery_ZCAnalysisModel>();
            var rcq = ConfigService.GetCQ(true);
            common.LoadCombox_IE(QCCbo, rcq);
            if (rcq.Count() == 0)
            {
                AyMessageBox.ShowError("没有测区！");
                return;
            }
            SearchModel.CboQCSelect = rcq.ElementAt(0).CQBH;
            SearchModel.IndexCQ = 1;

            CqChanged = inParam =>
            {
                if (QCCbo.Count == 0) return;
                int cqbh = (int)inParam;
                //工作面
                if (cqbh == -1)
                    SearchModel.CboQCSelect = -1;
                var rgzm = ConfigService.GetGZM(SearchModel.CboQCSelect);
                common.LoadCombox_IE(GZMCbo, rgzm);
                if (rgzm.Count() == 0) return;
                SearchModel.CboGZMSelect = rgzm.ElementAt(0).GZMBH;
                SearchModel.IndexGZM = 1;
            };
            CqChanged(SearchModel.CboQCSelect);
            Search = inParam =>
            {
                if (SearchModel.CboQCSelect == -1 || SearchModel.CboGZMSelect == -1)
                {
                    AyMessageBox.ShowError("请先选择测区和工作面！");
                    return;
                }
                if (AyCommon.ToInt(inParam) == 1)
                {
                    SearchModel.PageIndex = 1;
                }
                gzmbh = SearchModel.CboGZMSelect;
                if (SearchModel.PageIndex > 0)
                {
                    SearchData();
                }
                else
                {
                    SearchModel.PageIndex = 1;
                }
            };
            ExportExecl = inParam =>
            {
                //ExportExcel ExpEX = new Execl.ExportExcel();
                //try
                //{

                //    DataTable dt = new DataTable();
                //    dt = IenumerableToTable.AsDataTable<DataQuery_ZCAnalysisModel>(AllDatas);
                //    ExpEX.ExportGridExcel_Table("综采数据查询", dt, "", 18);
                //}
                //catch (Exception ex) { }
                SaveFileDialog saveDialog = new SaveFileDialog();
                saveDialog.DefaultExt = "xls";
                saveDialog.Filter = "Excel文件|*.xls";
                saveDialog.FileName = "综采分析数据导出";
                if (saveDialog.ShowDialog() != DialogResult.OK)
                {
                    return;
                }
                string saveFileName = saveDialog.FileName;
                if (!ExcelHelper.FileEditable(saveFileName))
                {
                    AyMessageBox.ShowError("文件被占用，请关闭文件" + saveFileName);
                    return;
                }
                var cond = DataQuery_ZCAnalysis_Conditon.Me.Cond;
                ViewBag.IsBusy = true;
                AyThread.Instance.RunNew(() =>
                {
                    if (cond.Count == 0) return;
                    dtStart = cond["dtStart"];
                    dtEnd = cond["dtEnd"];
                    _jq = cond["jq"];
                    zbhs = cond["bhs"];
                    DW = cond["MPa"];
                    DataZcService ds = new DataZcService();

                    string[] s = zbhs.Split(',');
                    int[] bhs = new int[s.Length];//编号列表
                    for (int b = 0; b < s.Length; b++)
                    {
                        bhs[b] = AyCommon.ToInt(s[b]);
                    }
                    int jq = AyCommon.ToInt(_jq);
                    DateTime db = AyCommon.ToDateTime(dtStart), de = AyCommon.ToDateTime(dtEnd) + new TimeSpan(23, 59, 59);
                    //db = new DateTime(2018, 12, 23); de = new DateTime(2018, 12, 25);
                    //统计总数
                    int TotalSum = ds.AnalysisCount(SearchModel.CboQCSelect, SearchModel.CboGZMSelect, bhs, db, de,jq);
                    if (TotalSum >= 65535)
                    {
                        AyMessageBox.ShowError("数据共" + TotalSum + "行，超过Excel限制(65535)，请缩短查询时间段！");
                        AyThread.Instance.RunUI(() =>
                        {
                            ViewBag.IsBusy = false;
                        });
                        return;
                    }
                    ds.ExportAnalysis(saveFileName,DW,SearchModel.CboQCSelect, SearchModel.CboGZMSelect, bhs, db, de,jq);
                    AyMessageBox.ShowInformation("已导出至" + saveFileName);
                    AyThread.Instance.RunUI(() =>
                    {
                        ViewBag.IsBusy = false;
                    });
                });
            };
            HSearch = inParam =>
            {
                if (SearchModel.CboQCSelect == -1 || SearchModel.CboGZMSelect == -1)
                {
                    AyMessageBox.ShowError("请先选择测区和工作面！");
                    return;
                }
                gzmbh = SearchModel.CboGZMSelect;
                ShowNavigationWindow("高级查询", "/Views/YFQ/DataQuery_ZCAnalysis_Conditon.xaml", 600, 500);
            };

        }


        public void SearchData()
        {
            var cond = DataQuery_ZCAnalysis_Conditon.Me.Cond;
            AllDatas.Clear();
            ViewBag.IsBusy = true;
            AyThread.Instance.RunNew(() =>
            {
                if (cond.Count == 0) return;
                dtStart = cond["dtStart"];
                dtEnd = cond["dtEnd"];
                _jq = cond["jq"];
                zbhs = cond["bhs"];
                DW = cond["MPa"];
                DataZcService ds = new DataZcService();

                string[] s = zbhs.Split(',');
                int[] bhs = new int[s.Length];//编号列表
                for (int b = 0; b < s.Length; b++)
                {
                    bhs[b] = AyCommon.ToInt(s[b]);
                }
                int jq = AyCommon.ToInt(_jq);
                DateTime db = AyCommon.ToDateTime(dtStart), de = AyCommon.ToDateTime(dtEnd) + new TimeSpan(23, 59, 59); 
                //db = new DateTime(2018, 9, 1); de = new DateTime(2018, 9, 2);
                //统计总数
                int TotalSum = ds.AnalysisCount(SearchModel.CboQCSelect, SearchModel.CboGZMSelect,
                     bhs, db, de, jq);
                var rs = ds.Analysis(SearchModel.CboQCSelect, SearchModel.CboGZMSelect,
                     bhs, db, de, jq,
                    SearchModel.PageIndex - 1, SearchModel.PageSize);

                //应用D[X]=E(X^2)-E(X)^2计算方差
                int count = 0;//计数
                double maxSum = 0, maxSum2 = 0, avgSum = 0, avgSum2 = 0;//单个传感器总和及平方总和
                double avgMax = 0, avgAvg = 0, stdMax = 0, stdAvg = 0;
                int lastBH = 0;

                AyThread.Instance.RunUI(() =>
                {
                    for (int i = 0; i < rs.Count(); i++)
                    {
                        var r = rs.ElementAt(i);
                        //新编号，计算完均值、均方差后回溯赋值
                        if (r.ZBH != rs.ElementAt(lastBH).ZBH)
                        {
                            //均值
                            avgMax = count == 0 ? 0 : maxSum / count;
                            avgAvg = count == 0 ? 0 : avgSum / count;
                            //均方差
                            stdMax = count == 0 ? 0 : Math.Sqrt(maxSum2 / count - avgMax * avgMax);
                            stdAvg = count == 0 ? 0 : Math.Sqrt(avgSum2 / count - avgAvg * avgAvg);
                            //回溯赋值
                            for (int j = lastBH; j < i; j++)
                            {
                                AllDatas[j].Zd_pjz = avgMax;
                                AllDatas[j].Zd_jfz = stdMax;
                                AllDatas[j].Zd_pj_jfz = avgMax + stdMax;
                                AllDatas[j].Pj_pjz = avgAvg;
                                AllDatas[j].Pj_jfz = stdAvg;
                                AllDatas[j].Pj_pj_jfz = avgAvg + stdAvg;
                            }
                            count = 0;
                            maxSum = 0; maxSum2 = 0; avgSum = 0; avgSum2 = 0;
                            lastBH = i;
                        }
                        DataQuery_ZCAnalysisModel cc = new DataQuery_ZCAnalysisModel();
                        cc.FZBH = r.ZBH;
                        cc.ZJBH = r.DYZJBH;
                        cc.AZWZ = r.WZ;
                        cc.ZDTIME = r.ZDATETIME;
                        cc.Zd_zdzl = DW == "MPa" ? r.MaxP12 : r.MaxF12;
                        maxSum += cc.Zd_zdzl;
                        maxSum2 += cc.Zd_zdzl * cc.Zd_zdzl;
                        cc.Pj_zdzl = DW == "MPa" ? r.AvgP12 : r.AvgF12;
                        avgSum += cc.Pj_zdzl;
                        avgSum2 += cc.Pj_zdzl * cc.Pj_zdzl;
                        count++;
                        AllDatas.Add(cc);
                    }
                    //回溯填写最后一个压力分站信息
                    if (rs.Count() > 0)
                    {
                        //均值
                        avgMax = count == 0 ? 0 : maxSum / count;
                        avgAvg = count == 0 ? 0 : avgSum / count;
                        //均方差
                        stdMax = count == 0 ? 0 : Math.Sqrt((maxSum2 / count - avgMax * avgMax) / count);
                        stdAvg = count == 0 ? 0 : Math.Sqrt((avgSum2 / count - avgAvg * avgAvg) / count);
                        //回溯赋值
                        for (int j = lastBH; j < rs.Count(); j++)
                        {
                            AllDatas[j].Zd_pjz = avgMax;
                            AllDatas[j].Zd_jfz = stdMax;
                            AllDatas[j].Zd_pj_jfz = avgMax + stdMax;
                            AllDatas[j].Pj_pjz = avgAvg;
                            AllDatas[j].Pj_jfz = stdAvg;
                            AllDatas[j].Pj_pj_jfz = avgAvg + stdAvg;
                        }
                    }
                    ViewBag.IsBusy = false;
                    if (AllDatas.Count > 0)
                    {
                        Result.Data = AllDatas;
                        Result.Total = TotalSum;
                        int _count = TotalSum / SearchModel.PageSize;
                        SearchModel.PageCount = TotalSum % SearchModel.PageSize == 0 ? _count : _count + 1;
                        int _start = (SearchModel.PageIndex - 1) * SearchModel.PageSize + 1;
                        SearchModel.Start = _start > 0 ? _start : 0;
                        int _end = SearchModel.PageIndex * SearchModel.PageSize;
                        SearchModel.End = _end > TotalSum ? TotalSum : _end;
                    }
                    else
                    {
                        SearchModel.PageIndex = 0;
                        AyMessageBox.ShowInformation("没有符合查询条件的记录！");
                    }
                });
            });
        }


        public ActionResult HSearch { get; private set; }

        public static NavigationWindow window = null;
        /// <summary>/// 使用NavigationWindow弹出页面/// </summary>

        private void ShowNavigationWindow(string title, string uri, int width, int height)
        {
            if (window == null)
            {
                window = new NavigationWindow();
                window.Title = title;
                window.Width = width;
                window.Height = height;
                window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                window.ResizeMode = ResizeMode.NoResize;
                window.Source = new Uri(uri, UriKind.Relative);
                window.ShowsNavigationUI = false;
                window.Closing += Window_Closing1;
            }
            else
            {
                DataQuery_ZCAnalysis_Conditon.Me.LoadBH();
            }
            window.ShowDialog();
        }

        private void Window_Closing1(object sender, System.ComponentModel.CancelEventArgs e)
        {
            //ConditonsModel.Name = cqm.Ckmc;
            DataQuery_ZCAnalysis_Conditon.Me.UpdateCond();
            SearchModel.PageIndex = 1;
            window.Hide();
            Me.SearchData();
            e.Cancel = true;
        }
    }
}
